﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;
using CP_SchoolForChildren_v0._1.Models.DataModel;
using CP_SchoolForChildren_v0._1.Models.RelatedModel;
using PagedList;
namespace CP_SchoolForChildren_v0._1.Controllers.FE
{

    public class QAController : Controller
    {
        SFCEntities db = new SFCEntities();

        public String CurrentUser()
        {
            string currentUserName = User.Identity.Name;
            return currentUserName;
        }

        public int currentUserID()
        {
            string name = CurrentUser();
            var user = from u in db.Users
                       where (u.UserName == name)
                       select u;
            int userid = user.First().UserID;
            return userid;
        }
        //
        // GET: /QA/

        public ActionResult Index(int? page, string searchString )
        {
            

            if (!String.IsNullOrEmpty(searchString))
            {
                 var keyword = searchString.Split(' ');
                 var question = from u in db.Users
                           from q in db.Questions
                           where u.UserID == q.UserID
                           where keyword.Any(val => q.QuestionContent.Contains(val))
                           select new QAModel
                           {
                               QuestionID = q.QuestionID,
                               UserID = u.UserID,
                               UserName = u.UserName,
                               QuestionContent = q.QuestionContent,
                               CreatedTime = q.CreatedTime,
                               AvatarURL = u.AvatarURL,
                           };
                 

                 List<Question> questionlist = (from q in db.Questions
                                                select q).ToList<Question>();

                 ViewBag.questionlist = questionlist;
                 ViewBag.Count = question.Count();
                 ViewBag.searchstring = searchString;
                 int pageSize = 10;
                 int pageNumber = (page ?? 1);
                 ModelState.Clear(); 
                 return View(question.OrderByDescending(q => q.CreatedTime).ToPagedList(pageNumber, pageSize));
            }
            else
            {
                var question = from u in db.Users
                               from q in db.Questions
                               where u.UserID == q.UserID
                               select new QAModel
                               {
                                   QuestionID = q.QuestionID,
                                   UserID = u.UserID,
                                   UserName = u.UserName,
                                   QuestionContent = q.QuestionContent,
                                   CreatedTime = q.CreatedTime,
                                   AvatarURL = u.AvatarURL,
                               };
               

                List<Question> questionlist = (from q in db.Questions
                                               select q).ToList<Question>();

                ViewBag.questionlist = questionlist;

                int pageSize = 10;
                int pageNumber = (page ?? 1);

                return View(question.OrderByDescending(q => q.CreatedTime).ToPagedList(pageNumber, pageSize));
            }       
           
            
        }
       

        // Create Question
        
        [Authorize(Roles="Member,Editor,Admin")]
        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Create(Question question)
        
            
            {
                try
                {
                    
                    
                        if (String.IsNullOrWhiteSpace(question.QuestionContent))
                        {
                           ModelState.AddModelError("", "Nội dung không được bỏ trống.");
                            return RedirectToAction("Index");
                        }
                        else if (ModelState.IsValid)
                        {
                            int userid = currentUserID();
                            try
                            {
                                var lastquestion = (from q in db.Questions
                                                    where q.UserID == userid
                                                    select q).OrderByDescending(q => q.CreatedTime).First();
                                DateTime lastactivity = lastquestion.CreatedTime;

                                TimeSpan beetween = DateTime.Now - lastactivity;
                                if (beetween.TotalSeconds >= 120)
                                {
                                    question.UserID = userid;
                                    question.CreatedTime = DateTime.Now;

                                    db.Questions.Add(question);
                                    db.SaveChanges();
                                    return RedirectToAction("Index", "QA");
                                }

                                else
                                {
                                    ViewBag.Message = "Sau 2 phút bạn mới được gửi câu hỏi tiếp theo";
                                    return RedirectToAction("Index");
                                }
                            }
                            
                            catch(Exception)
                            {
                                try
                                {
                                    question.UserID = userid;
                                    question.CreatedTime = DateTime.Now;

                                    db.Questions.Add(question);
                                    db.SaveChanges();
                                    return RedirectToAction("Index", "QA");
                                }
                                catch (Exception)
                                {

                                    ModelState.AddModelError("", "Đã có lỗi xảy ra trong quá trình gửi câu hỏi. Hãy kiểm tra kết nối và thử lại");
                                    return RedirectToAction("Index");
                                }
                            }
                                                                                 
                       }
                    
                }
                catch(Exception)
                {
                    ModelState.AddModelError("","Đã có lỗi xảy ra trong quá trình gửi câu hỏi. Hãy kiểm tra kết nối và thử lại");
                    return RedirectToAction("Index");
                }
            
            return RedirectToAction("Index", "QA");
        }
   
        //Delete question
        [Authorize]
        public ActionResult DeleteQuestion(int id)
        {
            try
            {
                int Currentuserid = currentUserID();
                var ID = from q in db.Questions
                         where q.QuestionID == id
                         select q;
                var user = from u in db.Users
                           where u.UserID == Currentuserid
                           select u;
                int CurrentUserRole = user.First().RoleID;
                int userID = ID.First().UserID;
                var role = db.UserRoles.Single(ur => ur.RoleName == "Admin");
                if (Currentuserid == userID || role.RoleID == CurrentUserRole)
                {
                    //delete all answer by question id
                    List<Answer> answer = (from a in db.Answers
                                           where (a.QuestionID == id)
                                           select a).ToList();
                    foreach (var item in answer)
                    {
                        db.Answers.Remove(item);
                        db.SaveChanges();
                    }
                    // delete question by question id
                    db.Questions.Remove(db.Questions.SingleOrDefault(q => q.QuestionID == id));
                    db.SaveChanges();
                    ViewBag.Message = "Câu hỏi của bạn đã được xóa";
                    return RedirectToAction("Index", "QA");
                } 
            }
            catch (Exception)
            {
                ModelState.AddModelError("","Đã có lỗi khi kết nối đến server. Hãy kiểm tra kết nối và thử lại");
                return RedirectToAction("Index", "QA");
            }

            return View();
        }

        public ActionResult Details(int id,int? page)
        {
            var question = from u in db.Users
                           from q in db.Questions
                           where u.UserID == q.UserID
                           where q.QuestionID == id
                           select new QAModel
                           {
                               QuestionID = q.QuestionID,
                               UserID = u.UserID,
                               UserName = u.UserName,
                               QuestionContent = q.QuestionContent,
                               CreatedTime = q.CreatedTime,
                               AvatarURL = u.AvatarURL,
                           };

            List<Answer> answer = (from a in db.Answers
                                   where (a.QuestionID == id)
                                   select a).ToList<Answer>();
            int pageSize = 10;
            int pageNumber = (page ?? 1);
            ViewBag.answer = answer.ToPagedList(pageNumber,pageSize);

            List<Question> questionlist = (from q in db.Questions
                                       select q).ToList<Question>();
            ViewBag.questionlist = questionlist;

            return View(question.First());
            
        }

        [HttpPost]
        public ActionResult Details(int id, string answercontent, int? page)
        {
            try
            {
              
                if (String.IsNullOrWhiteSpace(answercontent))
                {
                    var question = from u in db.Users
                                   from q in db.Questions
                                   where u.UserID == q.UserID
                                   where q.QuestionID == id
                                   select new QAModel
                                   {
                                       QuestionID = q.QuestionID,
                                       UserID = u.UserID,
                                       UserName = u.UserName,
                                       QuestionContent = q.QuestionContent,
                                       CreatedTime = q.CreatedTime,
                                      
                                   };
                    List<Answer> answer = (from a in db.Answers
                                           where (a.QuestionID == id)
                                           select a).ToList<Answer>();
                    ViewBag.answer = answer;

                    List<Question> questionlist = (from q in db.Questions
                                                   select q).ToList<Question>();
                    ViewBag.questionlist = questionlist;
                    ViewBag.Message = "Không được bỏ trống nội dung";
                    return RedirectToAction("Details", "QA", id);

                }
                
                else
                {
                    int userid = currentUserID();
                    try
                    {
                        var lastanswer = (from a in db.Answers
                                          where a.UserID == userid
                                          select a).OrderByDescending(a => a.CreatedTime).First();

                        DateTime lasttimeanswer = lastanswer.CreatedTime;
                        TimeSpan beetween = DateTime.Now - lasttimeanswer;
                        if (beetween.TotalSeconds >= 30)
                        {
                            var answers = new Answer
                            {
                                QuestionID = id,
                                AnswerContent = answercontent,
                                CreatedTime = DateTime.Now,
                                UserID = currentUserID()
                            };
                            db.Answers.Add(answers);
                            db.SaveChanges();
                            var question = from u in db.Users
                                           from q in db.Questions
                                           where u.UserID == q.UserID
                                           where q.QuestionID == id
                                           select new QAModel
                                           {
                                               QuestionID = q.QuestionID,
                                               UserID = u.UserID,
                                               UserName = u.UserName,
                                               QuestionContent = q.QuestionContent,
                                               CreatedTime = q.CreatedTime,
                                           };

                            List<Answer> answer = (from a in db.Answers
                                                   where (a.QuestionID == id)
                                                   select a).ToList<Answer>();
                            int pageSize = 10;
                            int pageNumber = (page ?? 1);
                            ViewBag.answer = answer.ToPagedList(pageNumber, pageSize);

                            List<Question> questionlist = (from q in db.Questions
                                                           select q).ToList<Question>();
                            ViewBag.questionlist = questionlist;

                            return RedirectToAction("Details", "QA", id);
                        }

                        else
                        {
                            var question = from u in db.Users
                                           from q in db.Questions
                                           where u.UserID == q.UserID
                                           where q.QuestionID == id
                                           select new QAModel
                                           {
                                               QuestionID = q.QuestionID,
                                               UserID = u.UserID,
                                               UserName = u.UserName,
                                               QuestionContent = q.QuestionContent,
                                               CreatedTime = q.CreatedTime,

                                           };
                            List<Answer> answer = (from a in db.Answers
                                                   where (a.QuestionID == id)
                                                   select a).ToList<Answer>();
                            int pageSize = 10;
                            int pageNumber = (page ?? 1);
                            ViewBag.answer = answer.ToPagedList(pageNumber, pageSize);

                            List<Question> questionlist = (from q in db.Questions
                                                           select q).ToList<Question>();
                            ViewBag.questionlist = questionlist;
                            ViewBag.Message = "Sau 30 giây bạn mới được gửi câu trả lời tiếp theo.";
                            ModelState.AddModelError("", "Sau 30 giây bạn mới được gửi câu trả lời tiếp theo.");
                            return RedirectToAction("Details", "QA", id);
                        }

                    }
                    catch(Exception)
                    {
                        try
                        {
                            var answers = new Answer
                            {
                                QuestionID = id,
                                AnswerContent = answercontent,
                                CreatedTime = DateTime.Now,
                                UserID = currentUserID()
                            };
                            db.Answers.Add(answers);
                            db.SaveChanges();
                            var question = from u in db.Users
                                           from q in db.Questions
                                           where u.UserID == q.UserID
                                           where q.QuestionID == id
                                           select new QAModel
                                           {
                                               QuestionID = q.QuestionID,
                                               UserID = u.UserID,
                                               UserName = u.UserName,
                                               QuestionContent = q.QuestionContent,
                                               CreatedTime = q.CreatedTime,
                                           };

                            List<Answer> answer = (from a in db.Answers
                                                   where (a.QuestionID == id)
                                                   select a).ToList<Answer>();
                            ViewBag.answer = answer;

                            List<Question> questionlist = (from q in db.Questions
                                                           select q).ToList<Question>();
                            ViewBag.questionlist = questionlist;

                            return RedirectToAction("Details", "QA", id);
                        }

                        catch(Exception)
                        {
                            ModelState.AddModelError("", "Đã có lỗi xảy ra, vui lòng kiểm tra kết nối và thử lại");
                            return View();  
                        }
                    }
                }
            }
            catch (Exception)
            {
                ModelState.AddModelError("", "Đã có lỗi xảy ra, vui lòng kiểm tra kết nối và thử lại");
                return View();
            }
        }

        public ActionResult ViewUserQuestion(int id, int? page)
        {
            List<Question> questionlist = (from q in db.Questions
                                           select q).ToList<Question>();
            ViewBag.questionlist = questionlist;    
                List<Question> question = (from q in db.Questions
                                           where q.UserID == id
                                           select q).ToList<Question>();
                int pageSize = 10;
                int pageNumber = (page ?? 1);
                return View(question.OrderByDescending(q => q.CreatedTime).ToPagedList(pageNumber,pageSize));           
        }

        public ActionResult ViewUserAnswer(int id, int? page)
        {
            List<Question> questionlist = (from q in db.Questions
                                           select q).ToList<Question>();
            ViewBag.questionlist = questionlist;
                List<Answer> answer = (from a in db.Answers
                                       where a.UserID == id
                                       select a).ToList<Answer>();
                int pageSize = 10;
                int pageNumber = (page ?? 1);
                return View(answer.OrderByDescending(a => a.CreatedTime).ToPagedList(pageNumber,pageSize));
        }

        public ActionResult DeleteAnswer(int id)
        {
            try
            {
                int Currentuserid = currentUserID();
                var ID = from a in db.Answers
                         where a.AnswerID == id
                         select a;
                var user = from u in db.Users
                           where u.UserID == Currentuserid
                           select u;
                int CurrentUserRole = user.First().RoleID;
                int userID = ID.First().UserID;
                int questionid = ID.First().QuestionID;
                var role = db.UserRoles.Single(ur => ur.RoleName == "Admin");
                if (Currentuserid == userID || role.RoleID == CurrentUserRole)
                {
                    db.Answers.Remove(db.Answers.SingleOrDefault(a => a.AnswerID == id));
                    db.SaveChanges();

                    ViewBag.Message = "Câu trả lời của bạn đã được xóa";
                    var question = from u in db.Users
                                   from q in db.Questions
                                   where u.UserID == q.UserID
                                   where q.QuestionID == questionid
                                   select new QAModel
                                   {
                                       QuestionID = q.QuestionID,
                                       UserID = u.UserID,
                                       UserName = u.UserName,
                                       QuestionContent = q.QuestionContent,
                                       CreatedTime = q.CreatedTime,
                                       AvatarURL = u.AvatarURL,
                                   };

                    List<Answer> answer = (from a in db.Answers
                                           where (a.QuestionID == questionid)
                                           select a).ToList<Answer>();
                    ViewBag.answer = answer;

                    List<Question> questionlist = (from q in db.Questions
                                                   select q).ToList<Question>();
                    ViewBag.questionlist = questionlist;
                    return RedirectToAction("Details", "QA", new { id = questionid });
                }
            }

            catch (Exception)
            {
                ModelState.AddModelError("", "Đã có lỗi khi kết nối đến server, hãy kiểm tra và thử lại");
                return RedirectToAction("Index", "QA");
            }

            return RedirectToAction("Index", "QA");
        }

        public string EditAnswer(string id, string value, int AnswerId, string RecordType)
        {
            var answer = (from a in db.Answers
                          where a.AnswerID == AnswerId
                          select a).First();
            try
            {
                answer.AnswerContent = value;
                db.Entry(answer).State = System.Data.EntityState.Modified;
                db.SaveChanges();
                return value;
            }
            catch(Exception)
            {
                return null;
            }
            
        }
    }
}
